<?php
namespace app\api\controller;

use think\Controller;
use think\Db;

class User extends Controller
{
    /**
     * 用户注册
     * @return array
     */
    public function register()
    {
        $postData = $this->request->post();
        
        // 验证必要参数
        if (empty($postData['username']) || empty($postData['password']) || empty($postData['email'])) {
            return ['code' => 400, 'msg' => '缺少必要参数'];
        }

        // 检查用户名和邮箱是否已存在
        if (Db::name('user')->where('username', $postData['username'])->find()) {
            return ['code' => 400, 'msg' => '用户名已存在'];
        }
        if (Db::name('user')->where('email', $postData['email'])->find()) {
            return ['code' => 400, 'msg' => '邮箱已存在'];
        }

        // 准备插入数据
        $data = [
            'username' => $postData['username'],
            'password' => password_hash($postData['password'], PASSWORD_DEFAULT),
            'email' => $postData['email'],
            'phone' => $postData['phone'] ?? null,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ];
        
        try {
            $result = Db::name('user')->insert($data);
            return $result ? 
                ['code' => 200, 'msg' => '注册成功'] : 
                ['code' => 500, 'msg' => '注册失败'];
        } catch (\Exception $e) {
            return ['code' => 500, 'msg' => '系统错误：' . $e->getMessage()];
        }
    }

    /**
     * 用户登录
     * @return array
     */
    public function login()
    {
        $postData = $this->request->post();
        
        // 验证必要参数
        if (empty($postData['username']) || empty($postData['password'])) {
            return ['code' => 400, 'msg' => '缺少必要参数'];
        }

        // 查询用户
        $user = Db::name('user')
            ->where('username', $postData['username'])
            ->find();
            
        if (!$user || !password_verify($postData['password'], $user['password'])) {
            return ['code' => 400, 'msg' => '用户名或密码错误'];
        }

        // 返回用户信息（实际项目中应返回token）
        return ['code' => 200, 'msg' => '登录成功', 'data' => [
            'id' => $user['id'],
            'username' => $user['username'],
            'email' => $user['email']
        ]];
    }
}
